package com.gutsyzhan.bilibili.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gutsyzhan.bilibili.constant.DanMuConstant;
import com.gutsyzhan.bilibili.dao.DanMuDao;
import com.gutsyzhan.bilibili.domain.DanMu;
import com.gutsyzhan.bilibili.service.DanMuService;
import com.mysql.jdbc.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class DanMuServiceImpl implements DanMuService {
    @Resource
    private DanMuDao danMuDao;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void addDanMu(DanMu danMu){
        danMuDao.addDanMu(danMu);
    }

    @Override
    public List<DanMu> getDanMus(Map<String, Object> params){
        return danMuDao.getDanMus(params);
    }

    @Override
    public void addDanMuToRedis(DanMu danMu){
        String key = DanMuConstant.VIDEO_DANMU_PREFIX + danMu.getVideoId();
        String value = redisTemplate.opsForValue().get(key);
        List<DanMu> list = new ArrayList<>();
        if(!StringUtils.isNullOrEmpty(value)) {
            list = JSONArray.parseArray(value, DanMu.class);
        }
        list.add(danMu);
        redisTemplate.opsForValue().set(key, JSONObject.toJSONString(danMu));
    }
}